package com.party.web.biz.openPlatform;

import com.party.api.dto.wechat.response.UploadTempMediaResponse;
import com.party.api.service.wechat.IWechatService;
import com.party.common.utils.StringUtils;
import com.party.common.utils.UUIDUtils;
import com.party.common.utils.refund.WechatPayUtils;
import com.party.core.model.wechatPlatform.WechatOpenMember;
import com.party.core.service.wechatPlatform.IWechatOpenMemberService;
import com.party.web.biz.file.FileBizService;
import com.party.web.utils.openPlatform.WXBizMsgCrypt;
import com.party.web.web.dto.input.wechatPlatform.ResolveMsgInput;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;

/**
 * 开放平台的第三方平台消息业务
 */
@Service
public class NotifyBizService {
    @Autowired
    private FileBizService fileBizService;

    @Autowired
    private IWechatService wechatService;

    @Autowired
    private IWechatOpenMemberService wechatOpenMemberService;

    protected static Logger logger = LoggerFactory.getLogger(NotifyBizService.class);

    /**
     * 1.获取推送component_verify_ticket协议
     *
     * @param responseData
     * @return
     * @throws Exception
     */
    public String resolveTicket(String token, String encodingAesKey, String responseData) throws Exception {
        Map<String, String> responseMap = WechatPayUtils.xmlToMap(responseData);
        String appId = responseMap.get("AppId");
        String encrypt = responseMap.get("Encrypt");
        logger.info("开始解密");
        WXBizMsgCrypt crypt = new WXBizMsgCrypt(token, encodingAesKey, appId);
        String decrypt = crypt.decrypt(encrypt);
        logger.info("解密结果{}", decrypt);
        Map<String, String> decryptMap = WechatPayUtils.xmlToMap(decrypt);
        String componentVerifyTicket = decryptMap.get("ComponentVerifyTicket");
        return componentVerifyTicket;
    }

    public Map<String, String> resolveMsg(String responseData, ResolveMsgInput input) throws Exception {
        logger.info("开始解密");
        WXBizMsgCrypt crypt = new WXBizMsgCrypt(input.getToken(), input.getEncodingAesKey(), input.getAppId());
        String decrypt = crypt.decryptMsg(input.getMsg_signature(), input.getTimestamp(), input.getNonce(), responseData);
        logger.info("解密结果{}", decrypt);
        Map<String, String> decryptMap = WechatPayUtils.xmlToMap(decrypt);
        return decryptMap;
    }


    public String encryptMsg(String requsetData, ResolveMsgInput input) throws  Exception{
        WXBizMsgCrypt crypt = new WXBizMsgCrypt(input.getToken(), input.getEncodingAesKey(), input.getAppId());
        return crypt.encryptMsg(requsetData, input.getTimestamp(), input.getNonce());
    }

    /**
     * 上传临时素材
     *
     * @param url      远程图片链接
     * @param memberId 用户id
     * @return
     */
    public String uploadTempMedia(String url, String memberId) throws Exception {
        File file = null;
        try {
            String imgFileUrl = fileBizService.getXmlPath() + "image" + File.separator + UUIDUtils.generateRandomUUID() + ".jpg";
            String imgPath = fileBizService.download(url, imgFileUrl);
            file = new File(imgPath);
            String accessToken = null;
            WechatOpenMember wechatOpenMember = wechatOpenMemberService.findByMemberId(memberId);
            if (null != wechatOpenMember) {
                accessToken = wechatOpenMember.getAuthorizerAccessToken();
            }
            UploadTempMediaResponse response = wechatService.uploadTempMedia(file, accessToken, "image");
            if (null == response || StringUtils.isEmpty(response.getMediaId())) {
                throw new Exception("上传二维码图片到临时素材异常");
            }
            return response.getMediaId();
        } catch (Exception e) {
            logger.error("上传二维码图片到临时素材异常", e);
            throw e;
        } finally {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
